<template>
  <div style="padding: 10px">
    <!-- 功能区域 -->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="add">新增</el-button>
      <el-upload
          action="http://localhost:9090/user/import"
          :headers="myHeaders"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          :limit="1"
          accept=".xlsx"
          style="display: inline-block; margin: 0 10px"
      >
        <el-button type="primary">导入</el-button>
      </el-upload>
      <el-button type="primary" @click="exportUser">导出</el-button>
    </div>
    <!-- 搜索区域 -->
    <div style="margin: 10px 0">
      <el-input
          v-model="queryParams.search"
          placeholder="请输入关键字"
          style="width: 20%"
          clearable
      ></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">
        查询
      </el-button>
    </div>
    <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
    >
      <el-table-column prop="id" label="ID" sortable></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="nickname" label="昵称"></el-table-column>
      <el-table-column prop="age" label="年龄" sortable></el-table-column>
      <el-table-column prop="sex" label="性别"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column label="角色">
        <template #default="scope">
          <span v-if="scope.row.role === 1">管理员</span>
          <span v-if="scope.row.role === 2">普通用户</span>
        </template>
      </el-table-column>
      <el-table-column label="头像">
        <template #default="scope">
          <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"
          >
            <template #error>
              <div
                  class="image-slot"
                  style="
                  text-align: center;
                  line-height: 49px;
                  border: 1px solid #ccc;
                "
              >
                <i class="el-icon-picture-outline"></i>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button
              size="mini"
              type="success"
              plain
              @click="showBooks(scope.row.bookList)"
          >查看图书列表
          </el-button>
          <el-button
              size="mini"
              type="primary"
              plain
              @click="handleEdit(scope.row)"
          >编辑
          </el-button>
          <el-popconfirm
              title="确定删除吗？"
              plain
              @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件 -->
    <div style="margin: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>

      <el-dialog title="用户拥有的图书列表" v-model="bookVis" width="30%">
        <el-table :data="bookList" stripe border>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="price" label="价格"></el-table-column>
        </el-table>
      </el-dialog>

      <!-- 添加修改框 -->
      <el-dialog title="提示" v-model="dialogVisible" width="30%" @close="closeDialog">
        <el-form :model="form" label-width="30%" ref="form" :rules="rules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="form.nickname" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="form.age" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio v-model="form.sex" label="男">男</el-radio>
            <el-radio v-model="form.sex" label="女">女</el-radio>
            <el-radio v-model="form.sex" label="未知">未知</el-radio>
          </el-form-item>
          <el-form-item label="地址">
            <el-input
                type="textarea"
                v-model="form.address"
                style="width: 80%"
            ></el-input>
          </el-form-item>
          <el-form-item label="账户余额">
            <el-input v-model="form.account" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-radio v-model="form.role" :label="1">管理员</el-radio>
            <el-radio v-model="form.role" :label="2">普通用户</el-radio>
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
                ref="upload"
                :show-file-list="false"
                :limit="1"
                :action="filesUploadUrl"
                :on-success="filesUploadSuccess"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
            <el-image
                v-if="
                form.avatar !== undefined &&
                form.avatar !== null &&
                form.avatar !== ''
              "
                style="width: 100px; height: 100px; margin-top: 20px"
                :src="form.avatar"
                :preview-src-list="[form.avatar]"
            ></el-image>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "User",
  components: {},
  data() {
    return {
      loading: true,
      queryParams: {
        search: "",
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisible: false,
      bookVis: false,
      form: {},
      tableData: [],
      bookList: [],
      filesUploadUrl:
          "http://" + window.server.filesUploadUrl + ":9090/files/upload",
      myHeaders: {token: localStorage.getItem("token")},
      rules: {
        username: [{required: true, message: "请输入姓名", trigger: "blur"}],
        age: [{required: true, message: "请输入年龄", trigger: "blur"}],
        sex: [{required: true, message: "请选择性别", trigger: "change"}],
        nickname: [{required: true, message: "请输入昵称", trigger: "blur"}],
        password: [{required: true, message: "请输入密码", trigger: "blur"}],
        role: [{required: true, message: "请选择角色", trigger: "change"}],
      },
    };
  },
  created() {
    this.load();
  },
  methods: {
    showBooks(books) {
      this.bookList = books;
      this.bookVis = true;
    },
    load() {
      this.loading = true;
      request.post("/user/query", this.queryParams).then((res) => {
        this.loading = false;
        // 数据
        this.tableData = res.data.records;
        // 总条数
        this.total = res.data.total;
      });
    },
    add() {
      this.dialogVisible = true;
      // 重置数据
      this.form = {
        role: 1,
        account: 10000,
      };
    },
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 密码不更改 置为空
          this.form.password = "";
          if (this.form.id) {
            let str = localStorage.getItem("user") || "{}";
            let loginUser = JSON.parse(str);
            // 更新
            request.put("/user", this.form).then((res) => {
              // 如果是当前登录用户更新 则更新数据
              if (loginUser.id === this.form.id) {
                // 触发Layout更新
                // this.$emit("userLocal");
                // 返回登录页面
                this.$router.push('/login');
              }
              if (res && res.code !== '0') {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              } else {
                this.$message({
                  type: "success",
                  message: "更新成功",
                });
              }
              this.load(); // 刷新表格数据
              this.dialogVisible = false; // 关闭弹窗
            });
          } else {
            // 新增
            request.post("/user", this.form).then((res) => {
              if (res && res.code !== '0') {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              } else {
                this.$message({
                  type: "success",
                  message: "新增成功",
                });
              }
              this.load(); // 刷新表格数据
              this.dialogVisible = false; // 关闭弹窗
            });
          }
        }
      });
    },
    handleEdit(row) {
      // 深拷贝
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    handleDelete(id) {
      request.delete("/user/" + id).then((res) => {
        if (res && res.code !== '0') {
          this.$message({
            type: "error",
            message: res.msg,
          });
        } else {
          this.$message({
            type: "success",
            message: "删除成功",
          });
        }
        this.load(); // 刷新表格数据
      });
    },
    filesUploadSuccess(res) {
      this.form.avatar = res.data;
    },
    handleUploadSuccess(res) {
      if (res.code === "0") {
        this.$message.success("导入成功");
        this.load();
      }
    },
    exportUser() {
      // 导出
      location.href =
          "http://" + window.server.filesUploadUrl + ":9090/user/export";
    },
    closeDialog() {
      // 清空form元素
      this.form = {};
      if (this.$refs["upload"]) {
        this.$refs["upload"].clearFiles(); // 清除历史文件列表
      }
      this.$refs["form"].resetFields();
    },
    handleSizeChange(pageSize) {
      // 改变当前每页的个数触发
      this.queryParams.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      // 改变当前页码触发
      this.queryParams.pageNum = pageNum;
      this.load();
    },
  },
};
</script>
